<template>
  <WidgetEditFormContainer v-model="innerDialogShow" :inline="inline">
    <q-card style="min-width: 500px">
      <template v-if="mode==='create'">
        <!--<q-img src="../../../assets/widgetPreview/RssWidgetPreview.png" alt="" :ratio="4/3"></q-img>-->
        <q-card-section>
          <div class="text-h6">自定义组件</div>
          <div>通过 HTML、CSS、JavaScript 编写完全自定义的组件 📊</div>
        </q-card-section>
      </template>
      <template v-if="mode==='update'">
        <q-card-section>
          <div class="text-h6">编辑富文本组件</div>
        </q-card-section>
      </template>
      <q-card>
        <q-form
            @submit="submitWidget"
            class="q-gutter-md"
        >
          <q-card-section class="q-pt-none">
            <CodeEditor v-model="htmlCode"></CodeEditor>
          </q-card-section>
          <q-card-section>
            <q-btn v-if="mode==='create'" type="submit"
                   color="green" icon-right="add" class="full-width"
            >确认添加
            </q-btn>
            <q-btn v-if="mode==='update'" type="submit"
                   color="green" class="full-width"
            >保存编辑
            </q-btn>
          </q-card-section>
        </q-form>
      </q-card>
    </q-card>
  </WidgetEditFormContainer>
</template>

<script>
import form from 'src/mixins/form'
import { genWidgetId } from 'src/utils/widget'
import WidgetEditFormContainer from '../../components/WidgetEditFormContainer'
import CodeEditor from '../../../../components/CodeEditor'

export default {
  name: 'CustomWidgetEditForm',
  mixins: [form],
  components: {
    WidgetEditFormContainer,
    CodeEditor
  },
  props: {
    defaultFormData: {
      type: Object,
      default: () => {
        const scriptTagName = 'script'
        return {
          data: {
            htmlCode: '<h1>Example Clock</h1>\n' +
                '<p>Time: <span id="time"></span></p>\n' +
                `<${scriptTagName}>\n\tsetInterval(() => time.textContent = new Date().toLocaleString(), 1000)\n</${scriptTagName}>`
          }
        }
      }
    }
  },
  data () {
    return {
      showCodeEditor: false,
      htmlCode: ''
    }
  },
  created () {
    this.htmlCode = this.formData.data.htmlCode
  },
  methods: {
    async submitWidget () {
      this.formData.data = {
        htmlCode: this.htmlCode
      }
      if (this.mode === 'create') {
        await this.createWidget({
          id: genWidgetId('CUSTOM'),
          type: 'CustomWidget',
          w: 4,
          h: 3
        })
      }
      if (this.mode === 'update') {
        await this.saveWidget()
      }
    }
  }
}
</script>
